#ifndef READERWRITER_UTILITIES_HEADER
#define READERWRITER_UTILITIES_HEADER

#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>

#define BUFFER_SIZE 50       
#define MAX_WRITE_LEN 20     
#define WAIT_TIME_IN_SECOND 1 

// Structure to manage shared resources for Readers and Writers
typedef struct {
    //读写互斥信号量，初始值为 1 
    //写者进入临界区前必须获得他，退出后释放确保写者独享访问
    //第一个进入临界区的读者获取后用于阻塞写者，而由最后一个离开的读者释放
    sem_t rw_mutex;    
    
    //互斥信号量，初始值为1
    //用于保护read_count变量的访问               	
    sem_t mutex;       
    
    //读者计数器，初始值为0
    //用于记录有多少个读者线程正在访问共享缓冲区                  
    int read_count;    

    char buffer[BUFFER_SIZE]; //共享字符缓冲区，读者写者共同操作的数据
    int buffer_len; //记录缓冲区当前内容长度   

    int exit_flag;  //程序退出标志，1表示退出

} ReaderWriterManager_t;


typedef struct
{
    ReaderWriterManager_t *rwMgr; // 指向共享管理器
    pthread_t tid;                // 线程ID
    int threadIdx;                // 线程的唯一标识符
} ThreadStruct_t;


ReaderWriterManager_t *createReaderWriterManager();
void initThreadStruct(ThreadStruct_t *threadStruct, ReaderWriterManager_t *rwMgr, int threadIdx);
void semWait(sem_t *sem);    
void semSignal(sem_t *sem);   
void semDestroy(sem_t *sem);  

#endif // READERWRITER_UTILITIES_HEADER
